#include "myStdio.h"

FILE_ *fopen_(const char* path_name,const char* mode)
{
   int flags = 0;
   int defaultMode = 0666;

   if(strcmp(mode,"r")==0)
   {
       flags |= O_RDONLY;  
   }
   else if(strcmp(mode,"w")==0)
   {
        flags |= (O_WRONLY | O_CREAT | O_TRUNC);
   }
   else if(strcmp(mode,"a")==0)
   {
        flags |= (O_WRONLY | O_CREAT | O_APPEND);
   }
   else 
   {
       //err
   }
   int fd = 0;
   if(flags & O_RDONLY) fd = open(path_name,flags);
   else fd = open(path_name,flags,defaultMode);
   if(fd<0)
   {
       const char* err = strerror(errno);
       write(2,err,strlen(err));
       return NULL;
   }

   FILE_* pf = (FILE_*)malloc(sizeof(FILE_));
   assert(pf);
   pf->flags = SYNC_LINE;//默认为行刷新
   pf->fileno = fd;
   pf->cap = SIZE;
   pf->size = 0;
   memset(pf->buffer,0,SIZE);

   return pf;

}

void fwrite_(const void* ptr,int num,FILE_* pf)
{
   memcpy(pf->buffer,ptr,num);
   pf->size+=num;

   //刷新策略
   if(pf->flags & SYNC_NOW)
   {
       fflush_(pf);
   }
   else if(pf->flags & SYNC_LINE)
   {
       if(pf->buffer[pf->size-1]=='\n')
       {
           write(pf->fileno,pf->buffer,pf->size);
           pf->size = 0;
       }
   }
   else if(pf->flags & SYNC_FULL)
   {
       if(pf->size == pf->cap)
       {
           write(pf->fileno,pf->buffer,pf->size);
           pf->size = 0;
       }
   }
   else 
   {

   }
}

void fclose_(FILE_* pf)
{
    fflush_(pf);
    close(pf->fileno);
}

void fflush_(FILE_* pf)
{
    if(pf->size>0) write(pf->fileno,pf->buffer,pf->size);
    pf->size = 0;

}
